package com.silence.kotlinapp

import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.support.v4.view.ViewPager
import com.silence.kotlinapp.activity.BaseActivity
import com.silence.kotlinapp.adapter.MainViewPagerAdapter
import com.silence.kotlinapp.fragment.BaseFragment
import com.silence.kotlinapp.fragment.GankAndroidFragment
import com.silence.kotlinapp.fragment.GankIosFragment
import com.silence.kotlinapp.fragment.GankWelfareFragment
import com.silence.kotlinapp.widget.ToolBarCommView
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : BaseActivity() {


    private lateinit var mFragments: LinkedList<BaseFragment>
    private lateinit var mViewPagerAdapter: MainViewPagerAdapter

    override fun getActivityContentView(): Int {
        return R.layout.activity_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
        initToolbar()
        initListener()

    }

    private fun initToolbar() {
        val toolBarCommView = ToolBarCommView(this)
        toolBarCommView.setTitle(view_pager.adapter!!.getPageTitle(0).toString())
        initToolbar(toolBarCommView)
    }

    private fun initView() {
        mFragments = LinkedList()
        mFragments.add(GankAndroidFragment.newInstance())
        mFragments.add(GankIosFragment.newInstance())
        mFragments.add(GankWelfareFragment.newInstance())

        mViewPagerAdapter = MainViewPagerAdapter(supportFragmentManager, mFragments)
        view_pager.adapter = mViewPagerAdapter

        tab_layout.setupWithViewPager(view_pager)
    }

    private fun initListener() {
        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                setToolbarTitle(view_pager.adapter!!.getPageTitle(position).toString())
            }

        })
    }

    inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
        val fragmentTransaction = beginTransaction()
        fragmentTransaction.func()
    }


    override fun onError(msg: String, code: Int) {
    }

    override fun onNetFinish() {
    }
}
